# -*- coding: utf-8 -*-
import ctypes
from ctypes import *
from ctypes.wintypes import UINT, DWORD 
import sys
import time
import os

 

VideoCapture_DLL=0

class CaptureCard:
    
    initSDK=1
    deviceNumber=0
    
    def __init__(self,deviceNum=0,resourceType=3,rFormat=0,rResolution=7):
        
        if VideoCapture_DLL:
            pass
        else:
            CaptureCard.getStatus()

        if  CaptureCard.deviceNumber:
            VideoCapture_DLL.videoCap_getDeviceType(0)
            szDeviceName=create_string_buffer('aaaaaa',256)
            VideoCapture_DLL.videoCap_getDeviceName(0,szDeviceName)
            DeviceSerialNum=create_string_buffer('aaaaaa',256)
            VideoCapture_DLL.videoCap_getDeviceSerialNum(0,DeviceSerialNum) 
             
            self.dwDeviceIndex=ctypes.c_long(0)
            self.phCaptureObject=ctypes.c_long(0)
             
            VideoCapture_DLL.videoCap_createCaptureObject(self.dwDeviceIndex,byref(self.phCaptureObject))
            if self.__setCaptureResource(resourceType):
                print("set CaputureResource is success")
            if self.__setResourceFormat(rFormat):
                print("set ResourceFormat is success")
            if self.__setResourceResolution(rResolution):
                print("set ResourceResolution is success")
        else:
            raise Exception("the Computer haven't avaiable CaptureCard ")
        

    
    
    def __setResourceResolution(self,rResolution=2):
        return not VideoCapture_DLL.videoCap_setVideoResolutionEx(self.phCaptureObject,rResolution)
        '''
            enum{                    
                VIDEORESOLUTION_640X480   = 0,                
                VIDEORESOLUTION_704X576   = 1,                
                VIDEORESOLUTION_720X480   = 2,                
                VIDEORESOLUTION_720X576   = 4,                      
                VIDEORESOLUTION_1920X1080 = 7,
                VIDEORESOLUTION_160X120   = 20, 
                VIDEORESOLUTION_176X144   = 21,
                VIDEORESOLUTION_240X176   = 22,
                VIDEORESOLUTION_240X180   = 23,
                VIDEORESOLUTION_320X240   = 24,
                VIDEORESOLUTION_352X240   = 25,
                VIDEORESOLUTION_352X288   = 26,
                VIDEORESOLUTION_640X240   = 27,
                VIDEORESOLUTION_640X288   = 28,
                VIDEORESOLUTION_720X240   = 29,
                VIDEORESOLUTION_720X288   = 30,
                VIDEORESOLUTION_80X60     = 31,
                VIDEORESOLUTION_88X72     = 32,
                VIDEORESOLUTION_128X96    = 33,
                VIDEORESOLUTION_640X576   = 34,
                VIDEORESOLUTION_180X120   = 37,
                VIDEORESOLUTION_180X144   = 38,
                VIDEORESOLUTION_360X240   = 39,    
                VIDEORESOLUTION_360X288   = 40,
                VIDEORESOLUTION_768X576   = 41,
                VIDEORESOLUTION_384x288   = 42,
                VIDEORESOLUTION_192x144   = 43,
                VIDEORESOLUTION_1280X720  = 44,
                VIDEORESOLUTION_1024X768  = 45,
                VIDEORESOLUTION_1280X800  = 46, 
                VIDEORESOLUTION_1280X1024 = 47,
                VIDEORESOLUTION_1440X900  = 48,
                VIDEORESOLUTION_1600X1200 = 49,
                VIDEORESOLUTION_1680X1050 = 50,
                VIDEORESOLUTION_800X600   = 51,
                VIDEORESOLUTION_1280X768  = 52,
                VIDEORESOLUTION_1360X768  = 53, 
                VIDEORESOLUTION_1152X864  = 54, 
                VIDEORESOLUTION_1280X960  = 55,
                VIDEORESOLUTION_702X576   = 56,
                VIDEORESOLUTION_720X400   = 57,
                VIDEORESOLUTION_1152X900  = 58,
                VIDEORESOLUTION_1360X1024 = 59,
                VIDEORESOLUTION_1366X768  = 60,
                VIDEORESOLUTION_1400X1050 = 61,
                VIDEORESOLUTION_1440X480  = 62,
                VIDEORESOLUTION_1440X576  = 63,
                VIDEORESOLUTION_1600X900  = 64, 
                VIDEORESOLUTION_1920X1200 = 65,
                VIDEORESOLUTION_1440X1080 = 66,
                VIDEORESOLUTION_1600X1024 = 67,
                VIDEORESOLUTION_3840X2160 = 68
            };
        '''  
    
    def __setResourceFormat(self,rFormat=0):
        
        return not VideoCapture_DLL.videoCap_setVideoFormat(self.phCaptureObject,rFormat)
        '''
            enum{                                        
                VIDEOFORMAT_NTSC = 0,
                VIDEOFORMAT_PAL  = 1,
            };
        '''
    
    def __setCaptureResource(self,resourceType=3):

        return not VideoCapture_DLL.videoCap_setVideoSource(self.phCaptureObject,resourceType)
        '''

            enum{
                    VIDEOSOURCE_COMPOSITE = 0,
                    VIDEOSOURCE_SVIDEO    = 1,
                    VIDEOSOURCE_COMPONENT = 2,
                    VIDEOSOURCE_HDMI      = 3,
                    VIDEOSOURCE_VGA       = 4,
                    VIDEOSOURCE_SDI       = 5,
                    VIDEOSOURCE_ASI       = 6,
                    VIDEOSOURCE_DVI       = 7
            };
        '''
    def takePicture(self,picPath,picType=2):
        fileType=os.path.basename(picPath)
        
        if "." in fileType:
            fileName=fileType.split(".")[0]
            fileType=fileType.split(".")[1]
            if fileType=="bmp":
                picType=1
            elif fileType=="jpg":
                picType=2
            elif fileType=="png":
                picType=3
            
            picPath=os.path.dirname(picPath)
            picPath=picPath+"\\"+fileName
        
        if picPath:
            if not VideoCapture_DLL.videoCap_startStreaming(self.phCaptureObject):
                
                lpFileName=c_char_p(picPath)
                if not VideoCapture_DLL.videoCap_singlePictureGet(self.phCaptureObject,picType,lpFileName):
                        
                    if not VideoCapture_DLL.videoCap_stopStreaming(self.phCaptureObject):
                        return True
                    else:
                        raise  Exception("the CaptureCard end error")
                else:
                    raise  Exception("the CaptureCard working error")
            else:
                raise Exception("the CaptureCard prepare error")
        else:
            raise AttributeError("the picture save path is null")
        '''
            // test type
            enum{
                IMAGETYPE_BMP  = 1,
                IMAGETYPE_JPG  = 2,
                IMAGETYPE_PNG  = 3,
                IMAGETYPE_TIFF = 4
            }
        '''


    def takeAudioWithTimes(self,picPath,time):
        if picPath:
            if not VideoCapture_DLL.videoCap_startStreaming(self.phCaptureObject):
                
                lpFileName=c_char_p(picPath)
		#laFileName=c_char_p('D:\\Tst_cap.wav')
                if not  VideoCapture_DLL.videoCap_captureAudioStart(self.phCaptureObject,time*1000,lpFileName):

                    if not VideoCapture_DLL.videoCap_stopStreaming(self.phCaptureObject):
                        return True
                    else:
                        raise  Exception("the CaptureCard end error")
                else:
                    raise  Exception("the CaptureCard working error")
            else:
                raise Exception("the CaptureCard prepare error")
        else:
            raise AttributeError("the picture save path is null")




    def takePictureWithtimes(self,picPath,times):
        if picPath:
            if not VideoCapture_DLL.videoCap_startStreaming(self.phCaptureObject):
                
                lpFileName=c_char_p(picPath)
                if not  VideoCapture_DLL.videoCap_videoSequenceStart(self.phCaptureObject,1,1,times*1000,picPath):
                        
                    if not VideoCapture_DLL.videoCap_stopStreaming(self.phCaptureObject):
                        return True
                    else:
                        raise  Exception("the CaptureCard end error")
                else:
                    raise  Exception("the CaptureCard working error")
            else:
                raise Exception("the CaptureCard prepare error")
        else:
            raise AttributeError("the picture save path is null")
        '''
            // test type
            enum{
                IMAGETYPE_BMP  = 1,
                IMAGETYPE_JPG  = 2,
                IMAGETYPE_PNG  = 3,
                IMAGETYPE_TIFF = 4
            }


	// video save type
	enum
	{
    	ST_BMP            = 0,
    	ST_JPG            = 1,
    	ST_AVI            = 2,
    	ST_CALLBACK       = 3,
    	ST_WAV            = 4,
    	ST_WMV            = 5,
    	ST_PNG            = 6,
    	ST_MPG            = 7,
    	ST_MP4            = 8,
    	ST_TIFF           = 9,
   	ST_CALLBACK_RGB24 = 10,
    	ST_CALLBACK_ARGB  = 11,
    	ST_TS             = 13
	};

        '''    

    def stop_stream(self):
        VideoCapture_DLL.videoCap_videoSequenceStop(self.phCaptureObject)

    def close(self):
        global VideoCapture_DLL
        
        if VideoCapture_DLL==None:
            return
        VideoCapture_DLL.videoCap_deleteCaptureObject(self.phCaptureObject)
        self.__releaseCaptureCardSDK()
        
        VideoCapture_DLL=None
        CaptureCard.initSDK=1

        
    def __releaseCaptureCardSDK(self):
        VideoCapture_DLL.videoCap_dllFree()
        
    @staticmethod
    def getStatus():
        
        if CaptureCard.initSDK:
            print("ininSDK run")
            global VideoCapture_DLL
            VideoCaptureDLLPath= sys.prefix+r"\Tools\AVM SDK\AVerCapAPI_PackageDLL.dll"
            VideoCapture_DLL=ctypes.windll.LoadLibrary(VideoCaptureDLLPath)

            # dll_path="C:\Program Files (x86)\AVerMedia\AVM SDK\SDK Pro\Lib\AVerCapAPI.dll"
            # CaptureCard.initSDK = VideoCapture_DLL.videoCap_dllInit(dll_path)

            CaptureCard.initSDK=VideoCapture_DLL.videoCap_dllInit(sys.prefix+r"\Tools\AVM SDK\SDK Basic\Lib\AVerCapAPI.dll")
            if not CaptureCard.initSDK :
                print("to init CaputerCard success")
                if VideoCapture_DLL.videoCap_getDeviceNum() >0:
                    CaptureCard.deviceNumber=VideoCapture_DLL.videoCap_getDeviceNum()
                    return True
                else:
                    return False
                
            else:
                return False
        
        else:
       
            return not bool(CaptureCard.initSDK)
            
     
    @staticmethod
    def getCaputureCardNumber():
        if not VideoCapture_DLL:
            if CaptureCard.getStatus():
           
                return list(range(CaptureCard.deviceNumber))
        else:
            return list(range(CaptureCard.deviceNumber))
            
def stop(capture):
    time.sleep(5)
    capture.stop_stream()
    print("停止")
    pass
      
if __name__=="__main__":
        a=CaptureCard()

        # a.takePicture(r"C:\Users\lij\Desktop\Avermedia\abc1.bmp")
        # a.takePictureWithtimes(r"D:/Test/1.jpg",5)

        begin = int(time.time())
        print("acb"+str(int(time.time())))
        import threading
        threading.Thread(target=stop,args=(a,)).start()
        a.takePictureWithtimes(r"D:/Test/"".jpg", 12)
        # a.stop_stream()
        print("bbb==============" + str(int(time.time())-begin))

        begin=int(time.time())
        print("***********" + str(int(time.time())))
        a.takePicture(r"D:/Test/qqq.jpg")
        print("====siginle=====" + str(int(time.time())-begin))
        a.close()
        time.sleep(5)
    


    
